import  pymysql

from producttest.caw.logger import Logger


def myConn(db_info):
    try:
        conn = pymysql.connect(user=db_info["user"],
                               password=db_info['pwd'],
                               database=db_info['dbname'],
                               host=db_info['host'],
                               port=db_info['port'],
                               charset=db_info['charset']
                               )

        logger = Logger()
        logger.info(f"-----数据库链接成功------")
        return conn
    except Exception as e:
        logger = Logger()
        logger.error(f"-----数据库链接失败------")


def myexecute(conn,sql):
    try:
        # 通过链接对象可以获取游标
        cursor1 = conn.cursor()

        # 通过游标执行数据库命令
        #cursor1.execute('select * from user')  执行查询命令
        # 执行修改命令
        cursor1.execute(sql)
        conn.commit()

        # 查询结果
        rall = cursor1.fetchall()
        # r = cursor1.fetchone()
        print(rall)
    except Exception:
        logger = Logger()
        logger.error(f"-----数据库执行失败------")
def myclose(conn):
    try:
        conn.close()
    except Exception:
        logger = Logger()
        logger.error(f"-----数据库关闭失败------")

# 删除所有操作 除了admin
def deleteAllProducts(db_info):
    conn = myConn(db_info)
    sql =f"delete from sys_product"
    myexecute(conn,sql)
    logger = Logger()
    logger.error(f"-----删除成功------")
    myclose(conn)

# 删除单个数据
def deleteoneproduct(db_info,productname):
    conn = myConn(db_info)
    sql = f"delete from sys_product where name = '{productname}'"
    myexecute(conn,sql)
    logger = Logger()
    logger.error(f"-----删除成功------")
    myclose(conn)

# 添加数据，只需要添加产品名称和代号即可
def addproduct(db_info,productname,productcode):
    conn =myConn(db_info)
    sql = (f"INSERT INTO `ranzhi`.`sys_product` (`id`, `name`, `code`, `type`, `status`, `line`, `desc`, `createdBy`, `createdDate`, `editedBy`,`editedDate`, `deleted`) "
           f"VALUES (0, '{productname}', '{productcode}', 'real', 'developing', 'default2', '', 'admin', '2025-09-02 16:31:18', '','2025-09-02 16:31:18', '1');")

    myexecute(conn,sql)
    logger = Logger()
    logger.error(f"----添加成功------")
    myclose(conn)

if __name__ == '__main__':
    db_info ={"user":"root","pwd":"!QAZ2wsx","host":"192.168.79.129","port":3306,"dbname":"ranzhi","charset":"utf8"}
    deleteAllProducts(db_info)
    addproduct(db_info,"wfrgf","842wgqif")
